<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Model\Documents as DocumentsModel;
use App\Http\Model\DocumentsParticiple;
use App\Http\Model\DocumentsParticipleId;
use \DB;
use PDO;

use Illuminate\Support\Facades\Cache;

use Fukuball\Jieba\Jieba;
use Fukuball\Jieba\Finalseg;

use Phpanalysis\Phpanalysis;


class DocumentController extends Controller
{
    protected $request;
    protected $documentsModel;
    protected $phpanalysisServer;

    public function __construct(Request $request)
    {
        $this->request        = $request;
        $this->documentsModel = new DocumentsModel();
    }

    /**
     *  文档入口
     * @param string $name
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index($name = 'index')
    {
        $name = preg_replace("/(\.html|\.php)?$/", '', $name);

        if (Cache::has($name)) {
            $info = unserialize(Cache::get($name));
        } else {
            if ($name == 'indexes.functions') {
                $dbh = new PDO("mysql:host=" . env('DB_HOST') . "; dbname=phpdoc", "dengqihua", "dengqihua520");
                $dbh->exec("SET CHARACTER SET UTF8");
                $stmt = $dbh->prepare('select a.*, b.content from documents as a left join documents_content as b on a.id = b.id where file_name = :file_name');
                $stmt->execute([':file_name' => $name]);
                $info = $stmt->fetch(PDO::FETCH_ASSOC);
            } else {
                $info = $this->documentsModel->where('file_name', $name)->first();
                $contentArr = $info->getContent->toArray();
                $info->content = $contentArr['content'];
                $info && $info = $info->toArray();
            }

            if ($info) {
                $info['prev_id'] && $info['prev_info'] = $this->documentsModel->where('id', $info['prev_id'])->first(['file_name', 'title'])->toArray();
                $info['next_id'] && $info['next_info'] = $this->documentsModel->where('id', $info['next_id'])->first(['file_name', 'title'])->toArray();
                $info['up_id'] && $info['up_info'] = $this->documentsModel->where('id', $info['up_id'])->first(['file_name', 'title'])->toArray();

                Cache::forever($name, serialize($info));
            } else {
                $info['title'] = $name;
            }
        }

        return view('index', ['info' => $info]);
    }

    /**
     * 更新浏览次数
     * @param $name
     */
    public function updatehits($name = null)
    {
        $name = preg_replace("/(\.html|\.php)?$/", '', $name);
        $name && $this->documentsModel->where('file_name', $name)->increment('hits');
    }

    /**
     * 搜索 - ajax方式
     * @param $keyword
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function searchAjax($keyword = null)
    {
        if ($this->request->ajax() && $keyword) {
            return $this->searchDeal($keyword);
        }
    }

    /**
     * 搜索 - 表单方式
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function searchForm()
    {
        $keyword = $this->request->input('keyword');
        $list    = $this->searchDeal($keyword, 100000);
        $data    = [
            'list'    => $list,
            'count'   => count($list),
            'title'   => "{$keyword} - 搜索结果",
            'keyword' => $keyword
        ];
        return view('search', $data);
    }

    /**
     * 查询搜索数据
     * @param $keyword
     * @param int $limit
     * @param int $page
     * @return array
     */
    private function searchDeal($keyword, $limit = 10, $page = 1)
    {
        if (!$keyword) {
            return [];
        }
        $this->phpanalysisServer = new PhpAnalysis('utf-8', 'utf-8', true);
        $documentParticipleModel = new DocumentsParticiple();

        $reg_list = $this->phpanalysis($keyword);

        $participle_id_list = $documentParticipleModel->where(function ($query) use ($reg_list) {
            foreach ($reg_list as $key => $val) {
                $query->orWhere('word', $val);
            }
        })->get(['id'])->toArray();

        $list  = [];
        $count = count($participle_id_list);
        if ($count) {
            $offset = ($page - 1) * $limit;
            $sql    = "SELECT file_name, title, keyword, hits FROM documents WHERE id IN (SELECT document_id FROM `documents_participle_id` WHERE %s) ORDER BY hits DESC LIMIT {$offset}, {$limit}";

            $participle_ids = [];
            foreach ($participle_id_list as $key => $val) {
                $participle_ids[] = 'participle_id = ' . $val['id'];
            }
            $str = implode(' OR ', $participle_ids);
            if ($count > 1) {
                $str .= ' GROUP BY document_id HAVING count(document_id) > 1';
            }
            $sql  = sprintf($sql, $str);
            $list = DB::select($sql);
        }

        return $list;
    }


    /**
     * 执行分词
     * @param $seg
     * @return array
     */
    protected function phpanalysis($seg)
    {
        //执行分词
        $this->phpanalysisServer->SetSource($seg);

        //多元切分
        $this->phpanalysisServer->differMax = true;

        //新词识别
        $this->phpanalysisServer->unitWord = true;

        //开始分析
        $this->phpanalysisServer->StartAnalysis(true);

        //返回分词结果集
        $reg_list = $this->phpanalysisServer->GetFinallyResult(' ', false);

        //结果集转换数组，去除空格，重新索引
        $reg_list && $reg_list = array_values(array_unique(array_filter(explode(' ', filter_mark(strtolower($reg_list))))));

        return $reg_list;
    }

    /**
     * 结巴分词
     * @param $seg
     */
    public function jieba_demo($seg)
    {
        dump(ceil(memory_get_usage() / 1024 / 1024) . 'MB');

        ini_set('memory_limit', '512M');
        Jieba::init();
        Finalseg::init();

        $seg_list = Jieba::cut($seg);
        dump($seg_list);

        dump(ceil(memory_get_usage() / 1024 / 1024) . 'MB');
    }

    /**
     * phpanalysis分词
     * @param $seg
     */
    public function phpanalysis_demo($seg)
    {
        dump(ceil(memory_get_usage() / 1024 / 1024) . 'MB');

        $pa = new PhpAnalysis('utf-8', 'utf-8', true);

        //载入词典
        //$pa->LoadDict();

        //执行分词
        $pa->SetSource($seg);

        //多元切分
        $pa->differMax = true;

        //新词识别
        $pa->unitWord = true;

        $pa->StartAnalysis(true);
        $reg_list = $pa->GetFinallyResult(' ', false);
        dump($reg_list);
        $reg_list && $reg_list = array_values(array_filter(explode(' ', filter_mark($reg_list))));


        dump($reg_list);

        dump(ceil(memory_get_usage() / 1024 / 1024) . 'MB');
    }
}